package com.ruoyi.web.controller.translation;

import java.util.concurrent.Semaphore;

/**
 * @Title:
 * @author: WYJ
 * @date: 2025/10/10
 */
public class BaiduTranslatorWithRateLimit {
    private final BaiduTranslator translator;
    private final Semaphore rateLimiter;
    private final int maxRetries;

    // 百度翻译免费版限制：1次/秒
    public BaiduTranslatorWithRateLimit() {
        this(1, 3);
    }

    public BaiduTranslatorWithRateLimit(int requestsPerSecond, int maxRetries) {
        this.translator = new BaiduTranslator();
        this.rateLimiter = new Semaphore(requestsPerSecond);
        this.maxRetries = maxRetries;
    }

    public String translateWithRetry(String text, String targetLang) {
        for (int attempt = 1; attempt <= maxRetries; attempt++) {
            try {
                rateLimiter.acquire();

                String result = translator.translate(text, targetLang);

                // 释放许可（在1秒后）
                new Thread(() -> {
                    try {
                        Thread.sleep(1000);
                        rateLimiter.release();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }).start();

                return result;

            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException("翻译被中断", e);
            } catch (Exception e) {
                System.err.printf("第%d次翻译尝试失败: %s\n", attempt, e.getMessage());

                if (attempt == maxRetries) {
                    throw new RuntimeException("翻译失败，已达最大重试次数", e);
                }

                // 指数退避
                try {
                    long delay = (long) Math.pow(2, attempt) * 1000;
                    Thread.sleep(delay);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException("重试被中断", ie);
                }
            }
        }
        return "翻译失败";
    }
}
